package com.coinworld.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @description:
 * @author:
 * @date: 2020/4/17 10:59
 */
@Component
public class AppContextUtil implements ApplicationContextAware, ResourceLoaderAware {

    private static ApplicationContext context;
    private static ResourceLoader resourceLoader;
    private static long STARTUP_DATE;
    private static String SERVER_ID;
    @Override
    public void setApplicationContext(ApplicationContext var1) throws BeansException {
        AppContextUtil.context = var1;
        STARTUP_DATE = context.getStartupDate();
        SERVER_ID = context.getId();

    }

    @Override
    public void setResourceLoader(ResourceLoader var1) {
        resourceLoader = var1;
    }

    public static Resource getResource(String location){
        return resourceLoader.getResource(location);
    }

    public static ApplicationContext getContext() {
        return context;
    }
    public static ResourceLoader getResourceLoader() {return resourceLoader; }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getServerId(){
        return SERVER_ID;
    }

    public static long getStartupDate(){
        return STARTUP_DATE;
    }

}
